package com.sgb.goods.view.activity.inquiry;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsActivityPublishingInquiryBinding;
import com.sgb.goods.entity.ConcreteEntity;
import com.sgb.goods.entity.GoodsInfoTypeEntity;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.entity.inquiry.FileItemInfoEntity;
import com.sgb.goods.entity.inquiry.GoodsInquiryEndTimeEntity;
import com.sgb.goods.entity.inquiry.InquiryDetailsEntity;
import com.sgb.goods.entity.inquiry.InvitedCompanyEntity;
import com.sgb.goods.entity.inquiry.MapLongAndLatEntity;
import com.sgb.goods.entity.inquiry.SupplierEntity;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.utils.FileUtils;
import com.sgb.goods.utils.base.BaseActivity;
import com.sgb.goods.view.adapter.inquiry.PhotoAlbumAdapter;
import com.sgb.goods.view.adapter.inquiry.SupplierDataAdapter;
import com.sgb.goods.viewmodel.inquiry.InquiryPublishingModel;
import com.sgb.goods.widget.InquiryGoodsItemView;
import com.sgb.goods.widget.pop.AddGoodsPopWindow;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.AttachmentStore;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.GlideEngine;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.view.areapopup.AddressEntity;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：询价-发布（编辑）
 *
 * @author qiangHeNoo
 * <p>
 * 时间：2021.12.10
 */
@Route(path = Constants.ARouter.AR_INQUIRY_PUBLISHING)
public class InquiryPublishingActivity extends BaseActivity<GoodsActivityPublishingInquiryBinding, InquiryPublishingModel> implements ItemInputTextView.OnWholeItemClickListener,
        InquiryGoodsItemView.TransferClickEventListener {
    private static final String TAG = "InquiryPublishingActivity";
    private String currentCity;
    private MapLongAndLatEntity currentSelectedLang = new MapLongAndLatEntity();
    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    private boolean isLoaded = false;
    /**
     * 二级联动数据
     */
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    /**
     * 三级联动数据
     */
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    /**
     * 可增删的商品类目最小临界值
     */
    private static final int MIN_GOODS_COUNT = 1;
    /**
     * 可增删的商品类目最大临界值
     */
    private static final int MAX_GOODS_COUNT = 10;
    private List<SupplierEntity> supplierEntityArrayList = new ArrayList<>();
    private List<InvitedCompanyEntity> inviteCompanyList = new ArrayList<>();
    /**
     * 询价要求相关数据
     */
    private List<GoodsInfoTypeEntity> goodsDeliverDemandList;
    private List<GoodsInfoTypeEntity> goodsLoadDemandList;
    private List<GoodsInfoTypeEntity> goodsUnloadDemandList;
    private List<GoodsInfoTypeEntity> goodsPayTypeList;
    private List<GoodsInfoTypeEntity> goodsPriceCheckList;
    private int goodsDeliverDemandPosition;
    private int goodsPayTypePosition;
    private int goodsUnloadDemandPosition;
    private int goodsLoadDemandPosition;
    private int goodsPriceCheckPosition;
    /**
     * 新增商品弹框
     */
    private AddGoodsPopWindow addGoodsPopWindow;
    private Calendar selectedDate;
    private Date today;
    public static final String KEY_GOOD_RESOURCE_ID = "resourceId";

    public static final String KEY_GOOD_FROM_WHERE = "fromWhere";
    /**
     * 商品详情模块询价
     */
    public static final String KEY_GOODS_DETAIL = "key_goods_detail";
    /**
     * 寻找供应商
     */
    public static final int REQUEST_CODE_FIND_SUPPLIER = 101;
    /**
     * 打开任务管理器
     */
    public static final int REQUEST_CODE_OPEN_FILE_CHOOSER = 102;
    /**
     * 选择收获定位
     */
    public static final int REQUEST_CODE_SELECT_ADDRESS = 103;

    /**
     * 当前编辑的商品view
     */
    private InquiryGoodsItemView mGoodsInfoView;

    /**
     * 当前添加商品的个数
     */
    private int goodsCount = 0;

    /**
     * 商品可以动态添加，此为存储商品对象的集合
     */
    private final List<InquiryGoodsItemView> goodsViewList = new ArrayList<>();

    /**
     * 供应商数据适配器
     */
    private SupplierDataAdapter supplierDataAdapter;
    private String resourceId;
    private String fromWhere;
    private PhotoAlbumAdapter albumAdapter;
    private static final int MAX_COUNT = 10;
    /**
     *
     **/
    private List<FileItemInfoEntity> fileItemInformation = new ArrayList<>();
    private List<LocalMedia> localMedia = new ArrayList<>();


    public static void start(Context context, String goodsSourceId, String fromWhere) {
        Intent intent = new Intent(context, InquiryPublishingActivity.class);
        intent.putExtra(KEY_GOOD_RESOURCE_ID, goodsSourceId);
        intent.putExtra(KEY_GOOD_FROM_WHERE, fromWhere);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, Serializable serializable) {
        Intent intent = new Intent(context, InquiryPublishingActivity.class);
        intent.putExtra(KEY_GOODS_DETAIL, serializable);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.goods_activity_publishing_inquiry;
    }

    @Override
    protected void initObserve() {
        mViewModel.mapLongAndLatEntity.observe(InquiryPublishingActivity.this, this::fillCurrentAddressLadling);
        mViewModel.addressEntity.observe(InquiryPublishingActivity.this, this::showAddressPop);
        mViewModel.goodsDeliverTypeEntity.observe(InquiryPublishingActivity.this, goodsDeliverTypeEntity -> showDeliverDemand(goodsDeliverTypeEntity.getGoodsInfoTypeEntities(), goodsDeliverTypeEntity.isFlog()));
        mViewModel.goodsLoadTypeEntity.observe(InquiryPublishingActivity.this, goodsLoadTypeEntity -> showLoadDemand(goodsLoadTypeEntity.getGoodsInfoTypeEntities(), goodsLoadTypeEntity.isFlog()));
        mViewModel.goodsUnloadTypeEntity.observe(InquiryPublishingActivity.this, goodsUnloadTypeEntity -> showUnloadDemand(goodsUnloadTypeEntity.getGoodsInfoTypeEntities(), goodsUnloadTypeEntity.isFlog()));
        mViewModel.goodsInquiryTypeEntity.observe(InquiryPublishingActivity.this, goodsInquiryTypeEntity -> showPriceCheck(goodsInquiryTypeEntity.getGoodsInfoTypeEntities(), goodsInquiryTypeEntity.isFlog()));
        mViewModel.goodsPayTypeEntity.observe(InquiryPublishingActivity.this, goodsPayTypeEntity -> showPayType(goodsPayTypeEntity.getGoodsInfoTypeEntities(), goodsPayTypeEntity.isFlog()));
        mViewModel.vipSupplierEntity.observe(InquiryPublishingActivity.this, this::showVipSupplier);
        mViewModel.inquiryDetailsEntity.observe(InquiryPublishingActivity.this, this::initChangeData);
        mViewModel.goodsUploadFileResponseEntity.observe(InquiryPublishingActivity.this, goodsUploadFileResponseEntity -> {
            uploadImageSuccess(goodsUploadFileResponseEntity.imageUrl, goodsUploadFileResponseEntity.file, goodsUploadFileResponseEntity.completeNum, goodsUploadFileResponseEntity.isEnding);
        });
        mViewModel.isPublishFinished.observe(InquiryPublishingActivity.this, aBoolean -> {
            mDataBinding.goodsPublishConfirm.setClickable(false);
            if (!TextUtils.isEmpty(this.resourceId)&& !"2".equals(fromWhere)) {
                MToast.showToast(this, "询价修改成功!");
            } else {
                MToast.showToast(this, "询价发布成功!");
            }
            finish();
        });
        mViewModel.isButtonEnable.observe(InquiryPublishingActivity.this, aBoolean -> {
            if (aBoolean) {
                mDataBinding.goodsPublishConfirm.setClickable(true);
            }
        });
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(InquiryPublishingModel.class, BR.viewModel);
    }

    @Override
    protected void initListener() {
        mDataBinding.head.ivBack.setOnClickListener(v -> finish());
        mDataBinding.goodsPublishConfirm.setOnClickListener(v -> {
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setItemList(buildGoodsList());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setConcreteList(buildConcreteList());
            changeGoodsStates();
            if (!isFillGoods()) {
                MToast.showToast(InquiryPublishingActivity.this, "请完善必填信息");
                return;
            }
            buildPriceCheckData();
            if (isInputValid()) {
                mViewModel.publishPriceCheck(mViewModel.priceCheckEntity.get());
            }
        });
        mDataBinding.goodsAddGoods.setOnClickListener(v -> showAddGoodsPop());

        mDataBinding.goodsRlInvite.setOnClickListener(v -> {
            List<SupplierEntity> supplierEntityList = supplierDataAdapter.getData();
            List<String> companyListId = new ArrayList<>();
            for (int i = 0; i < supplierEntityList.size(); i++) {
                companyListId.add(supplierEntityList.get(i).getNo());
            }
            Intent intent = new Intent(this, FindInquirySupplierActivity.class);
            intent.putExtra("newData", (Serializable) supplierEntityList);
            startActivityForResult(intent, REQUEST_CODE_FIND_SUPPLIER);
        });

        mDataBinding.goodsUploadFile.setOnClickListener(v -> openAlbum());
    }

    @Override
    protected void init() {
        super.init();
        initView();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        fillPublishCompany();
        initPopWindow();
        mViewModel.getDeliverDemand(true);
        mViewModel.getLoadDemand(true);
        mViewModel.getUnloadDemand(true);
        mViewModel.getPayType(true);
        mViewModel.getPriceCheckDemand(true);
        this.resourceId = getIntent().getStringExtra(KEY_GOOD_RESOURCE_ID);
        this.fromWhere = getIntent().getStringExtra(KEY_GOOD_FROM_WHERE);
        if (this.resourceId != null && !TextUtils.isEmpty(this.resourceId)) {
            if ("2".equals(fromWhere)) {
                mDataBinding.goodsPublishConfirm.setText("确认发布");
                mDataBinding.head.title.setText("发布询价");
                initEditView();
            } else {
                mDataBinding.goodsPublishConfirm.setText("确认修改");
                mDataBinding.head.title.setText("修改询价");
                initEditView();
            }
        } else if (getIntent().getSerializableExtra(KEY_GOODS_DETAIL) != null) {
            //商品详情点击过来
            if (getIntent().getSerializableExtra(KEY_GOODS_DETAIL) instanceof InquiryDetailsEntity) {
                InquiryDetailsEntity enquiryDetailsEntity = (InquiryDetailsEntity) getIntent().getSerializableExtra(KEY_GOODS_DETAIL);
                initChangeData(enquiryDetailsEntity);
            }
            mDataBinding.head.title.setText("发布询价");
            mDataBinding.goodsPublishConfirm.setText("确认发布");
        } else {
            initGoodsView();
            mDataBinding.head.title.setText("发布询价");
            mDataBinding.goodsPublishConfirm.setText("确认发布");
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }

    private void initView() {
        mDataBinding.goodsRate.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mDataBinding.goodsEndTime.setOnWholeItemClickListener(this);//截至时间
        mDataBinding.goodsReceiveArea.setOnWholeItemClickListener(this);//收货地区
        mDataBinding.goodsReceiveAddress.setOnWholeItemClickListener(this);//详细地址
        mDataBinding.goodsDeliverDemand.setOnWholeItemClickListener(this);//送货要求
        mDataBinding.goodsLoadDemand.setOnWholeItemClickListener(this);//装车方式
        mDataBinding.goodsUnloadDemand.setOnWholeItemClickListener(this);//卸车要求
        mDataBinding.goodsPayType.setOnWholeItemClickListener(this);//付款方式·
        mDataBinding.goodsCheckType.setOnWholeItemClickListener(this);//询价方式
        mDataBinding.goodsContactNumber.setInputType(InputType.TYPE_CLASS_NUMBER);
        initRecyclerView();
    }

    private void initChangeData(InquiryDetailsEntity detailEntity) {
        if (detailEntity != null) {
            List<ConcreteEntity> list = detailEntity.getConcreteList();
            if (list != null && list.size() != 0) {
                for (ConcreteEntity concrete : list) {
                    addGoodsView(InquiryPublishingActivity.this, concrete, false);
                }
            }

            List<GoodsItemEntity> itemList = detailEntity.getItemList();
            if (itemList != null && itemList.size() != 0) {
                for (GoodsItemEntity goodsItem : itemList) {
                    addGoodsView(InquiryPublishingActivity.this, goodsItem, false);
                }
            }
            List<InquiryDetailsEntity.InviteCompanyList> invitedCompanies = detailEntity.getInviteCompanyList();
            if (invitedCompanies != null && invitedCompanies.size() != 0) {
                //商品详情组装的数据和再来一单请求到的数据可以进行删除供应商
                if (TextUtils.isEmpty(detailEntity.getNo()) || "2".equals(fromWhere)) {
                    fillSupplierView(buildSupplierEntityList(invitedCompanies, false));
                } else {
                    fillSupplierView(buildSupplierEntityList(invitedCompanies, true));
                }

            }
            if (detailEntity.getDeadlineTime() != 0) {
                mDataBinding.goodsEndTime.setContent(DateUtils.timestampTo13Date3(detailEntity.getDeadlineTime()));
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeadlineTime(String.valueOf(detailEntity.getDeadlineTime()));
            }
            if (!TextUtils.isEmpty(detailEntity.getProvinceName()) && !TextUtils.isEmpty(detailEntity.getCityName()) && !TextUtils.isEmpty(detailEntity.getDistrictName())) {
                mDataBinding.goodsReceiveArea.setContent(detailEntity.getProvinceName() + "-" + detailEntity.getCityName() + "-" + detailEntity.getDistrictName());
            } else if (!TextUtils.isEmpty(detailEntity.getProvinceName()) && !TextUtils.isEmpty(detailEntity.getCityName()) && TextUtils.isEmpty(detailEntity.getDistrictName())) {
                mDataBinding.goodsReceiveArea.setContent(detailEntity.getProvinceName() + "-" + detailEntity.getCityName());
            }
            if (!TextUtils.isEmpty(detailEntity.getProvinceName()) && !TextUtils.isEmpty(detailEntity.getProvinceNo())) {
                //省
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setProvinceName(detailEntity.getProvinceName());
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setProvinceNo(detailEntity.getProvinceNo());
            }

            if (!TextUtils.isEmpty(detailEntity.getCityName()) && !TextUtils.isEmpty(detailEntity.getCityNo())) {
                //市
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setCityName(detailEntity.getCityName());
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setCityNo(detailEntity.getCityNo());
            }

            if (!TextUtils.isEmpty(detailEntity.getDistrictName()) && !TextUtils.isEmpty(detailEntity.getDistrictNo())) {
                //区
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDistrictName(detailEntity.getDistrictName());
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDistrictNo(detailEntity.getDistrictNo());
            }
            if (!TextUtils.isEmpty(detailEntity.getProvinceNo()) && !TextUtils.isEmpty(detailEntity.getCityNo()) && !TextUtils.isEmpty(detailEntity.getDistrictNo())) {
                mViewModel.getSelectedAddressLadling(detailEntity.getProvinceNo(), detailEntity.getCityNo(), detailEntity.getDistrictNo());
            }
            if (!TextUtils.isEmpty(detailEntity.getDetailAddress())) {
                mDataBinding.goodsReceiveAddress.setContent(detailEntity.getDetailAddress());
            }
            if (detailEntity.getTaxRate() != 0) {
                mDataBinding.goodsRate.setContent(String.valueOf(detailEntity.getTaxRate()));
            }
            //送货要求
            int goodsDeliverIndex = detailEntity.getDeliveryRequire();
            mDataBinding.goodsDeliverDemand.setContent(getContentValue(goodsDeliverDemandList, String.valueOf(goodsDeliverIndex)));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeliveryRequire(String.valueOf(goodsDeliverIndex));

            //装车要求
            mDataBinding.goodsLoadDemand.setContent(getContentValue(goodsLoadDemandList, detailEntity.getLoadingRequire()));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLoadingRequire(detailEntity.getLoadingRequire());

            //卸车要求
            int goodsUnloadIndex = detailEntity.getUnloadRequire();
            mDataBinding.goodsUnloadDemand.setContent(getContentValue(goodsUnloadDemandList, String.valueOf(goodsUnloadIndex)));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setUnloadRequire(String.valueOf(goodsUnloadIndex));

            //付款要求
            mDataBinding.goodsPayType.setContent(getContentValue(goodsPayTypeList, String.valueOf(detailEntity.getTransactionMethod())));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setTransactionMethod(String.valueOf(detailEntity.getTransactionMethod()));

            //询价要求
            int typeIndex = detailEntity.getType();
            mDataBinding.goodsCheckType.setContent(getContentValue(goodsPriceCheckList, String.valueOf(typeIndex)));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setType(String.valueOf(typeIndex));

            mDataBinding.goodsRequirements.setText(detailEntity.getQualityDesc());
            mDataBinding.goodsFeature.setText(detailEntity.getFeaturesDesc());
            List<FileItemInfoEntity> fileItemInformation = detailEntity.getFilePath();
            if (fileItemInformation != null && fileItemInformation.size() != 0) {
                this.fileItemInformation = fileItemInformation;
                albumAdapter.setNewData(this.fileItemInformation);
                setUploadButtonEnable();
            }
            mDataBinding.goodsNote.setText(detailEntity.getDescribe());
            if (!TextUtils.isEmpty(detailEntity.getContacts())) {
                mDataBinding.goodsContactName.setContent(detailEntity.getContacts());
            }
            if (detailEntity.getContactNumber() != null && !"".equals(detailEntity.getContactNumber())) {
                mDataBinding.goodsContactNumber.setContent(detailEntity.getContactNumber());
            }
            fillPublishCompany();
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setId(String.valueOf(detailEntity.getId()));
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLatitude(detailEntity.getLatitude());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLongitude(detailEntity.getLongitude());
        }
    }

    /**
     * 根据接口返回的
     *
     * @return
     */
    private String getContentValue(List<GoodsInfoTypeEntity> entity3List, String key) {
        if (entity3List == null || entity3List.size() == 0) {
            return "";
        }
        for (GoodsInfoTypeEntity entity : entity3List) {
            if (entity.getNo().equals(key)) {
                return entity.getName();
            }
        }
        return "";
    }

    /**
     * 创建供应商列表数据
     *
     * @param invitedCompanies
     * @return
     */
    private List<SupplierEntity> buildSupplierEntityList(List<InquiryDetailsEntity.InviteCompanyList> invitedCompanies, boolean isEdit) {
        List<SupplierEntity> supplierEntityList = new ArrayList<>();
        for (InquiryDetailsEntity.InviteCompanyList inviteCompanyList : invitedCompanies) {
            SupplierEntity supplierEntity = new SupplierEntity();
            supplierEntity.setFlag(inviteCompanyList.getFlag());
            supplierEntity.setName(inviteCompanyList.getSupplierName());
            supplierEntity.setNo(inviteCompanyList.getSupplier());
            supplierEntity.setSupplierType(inviteCompanyList.getSupplierType());
            supplierEntity.setSelected(true);
            if (isEdit) {
                supplierEntity.setModify(true);
            } else {
                supplierEntity.setModify(false);
            }
            supplierEntityList.add(supplierEntity);
        }
        return supplierEntityList;
    }

    private void initRecyclerView() {
        if (supplierDataAdapter == null) {
            supplierDataAdapter = new SupplierDataAdapter(InquiryPublishingActivity.this);
            supplierDataAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.goods_delete_supplier) {
                    supplierDataAdapter.remove(position);
                    supplierEntityArrayList = supplierDataAdapter.getData();
                    buildInvitedCompanyList(supplierEntityArrayList);
                }
            });
        }
        int dimension = (int) getResources().getDimension(R.dimen.dp5) * 2;
        int leftDimension = (int) getResources().getDimension(R.dimen.dp16);
        mDataBinding.goodsSupplierView.addItemDecoration(new RecyclerCustomDecoration(leftDimension,
                leftDimension,
                0,
                dimension, getResources().getColor(R.color.colorWhite)));
        mDataBinding.goodsSupplierView.setLayoutManager(new LinearLayoutManager(InquiryPublishingActivity.this));
        mDataBinding.goodsSupplierView.setAdapter(supplierDataAdapter);
        mDataBinding.goodsSupplierView.setVisibility(View.GONE);
        if (albumAdapter == null) {
            albumAdapter = new PhotoAlbumAdapter(InquiryPublishingActivity.this);
            albumAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (fileItemInformation != null && fileItemInformation.size() > position) {
                    fileItemInformation.remove(position);
                    albumAdapter.setNewData(fileItemInformation);
                    setUploadButtonEnable();
                }
            });
        }
        mDataBinding.goodsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDataBinding.goodsRecyclerView.setAdapter(albumAdapter);
    }

    /**
     * 修改询价发布信息
     */
    private void initEditView() {
        mViewModel.getInquiryDetails(getIntent().getStringExtra(KEY_GOOD_RESOURCE_ID));
    }

    private void initGoodsView() {
        Serializable serializable = getIntent().getSerializableExtra("GOOD_ITEM");
        addGoodsView(this, serializable, false);
        List<InquiryDetailsEntity.InviteCompanyList> invitedCompanies = getCacheCompanyEntity();
        if (invitedCompanies != null && invitedCompanies.size() != 0) {
            fillSupplierView(buildSupplierEntityList(invitedCompanies, false));
        }
    }

    private List<InquiryDetailsEntity.InviteCompanyList> getCacheCompanyEntity() {
        Type type = new TypeToken<List<InquiryDetailsEntity.InviteCompanyList>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CacheGoodsSupplierModel, type);
        if (object != null) {
            try {
                List<InquiryDetailsEntity.InviteCompanyList> cacheList = (List<InquiryDetailsEntity.InviteCompanyList>) object;
                DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CacheGoodsSupplierModel, "");
                return cacheList;
            } catch (Exception exception) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 填充发布企业字段
     */
    private void fillPublishCompany() {
        //类型 0个人 1企业 2团队 3组织
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        String realName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String phoneNumber = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        mDataBinding.goodsContactName.setContent(realName);
        mDataBinding.goodsContactNumber.setContent(phoneNumber);
        if (1 == type) {
            String company = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
            mDataBinding.goodsInquiryCompanyName.setVisibility(View.VISIBLE);
            mDataBinding.goodsInquiryCompanyName.setContent(company);
        } else {
            mDataBinding.goodsInquiryCompanyName.setVisibility(View.GONE);
            mDataBinding.goodsInquiryCompanyName.setContent("");
        }
    }

    /**
     * 初始化商品各个属性的弹窗（包含属性选取后的逻辑）
     */
    private void initPopWindow() {
        if (addGoodsPopWindow == null) {
            addGoodsPopWindow = new AddGoodsPopWindow(InquiryPublishingActivity.this);
        }
        addGoodsPopWindow.setBgView(mDataBinding.goodsGrayView);
        addGoodsPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        addGoodsPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        addGoodsPopWindow.setOnClickCallBack(new AddGoodsPopWindow.OnClickCallBack() {
            @Override
            public void copy() {
                //复制一条商品
                addGoodsView(InquiryPublishingActivity.this, getLastGoodsView(), true);
            }

            @Override
            public void add() {
                //新增一条商品
                addGoodsView(InquiryPublishingActivity.this, null, false);
            }

            @Override
            public void cancel() {
            }
        });
    }

    private Serializable getLastGoodsView() {
        int size = goodsViewList.size();
        if (size > 0) {
            InquiryGoodsItemView infoView = goodsViewList.get(size - 1);
            if (infoView.isChoiceST()) {
                infoView.getConcreteItem().setNum(infoView.getGoodsAmount());
                ConcreteEntity concreteEntity = new ConcreteEntity();
                concreteEntity.setConfig(infoView.getConcreteItem().getConfig());
                concreteEntity.setDeliveryMethod(infoView.getConcreteItem().getDeliveryMethod());
                concreteEntity.setFcatName(infoView.getConcreteItem().getFcatName());
                concreteEntity.setFcategory(infoView.getConcreteItem().getFcategory());
                concreteEntity.setNum(infoView.getConcreteItem().getNum());
                concreteEntity.setScatName(infoView.getConcreteItem().getScatName());
                concreteEntity.setScategory(infoView.getConcreteItem().getScategory());
                concreteEntity.setSort(infoView.getConcreteItem().getSort());
                concreteEntity.setStrongLevel(infoView.getConcreteItem().getStrongLevel());
                concreteEntity.setTcatName(infoView.getConcreteItem().getTcatName());
                concreteEntity.setTcategory(infoView.getConcreteItem().getTcategory());
                concreteEntity.setUnit(infoView.getConcreteItem().getUnit());
                concreteEntity.setCartTitle(infoView.getConcreteItem().getCartTitle());
                concreteEntity.setAdmixtureFactList(infoView.getConcreteItem().getAdmixtureFactList());
                return concreteEntity;
            } else {
                infoView.getGoodsItem().setNum(infoView.getGoodsAmount());
                GoodsItemEntity goodsItemEntity = new GoodsItemEntity();
                goodsItemEntity.setNum(infoView.getGoodsItem().getNum());
                goodsItemEntity.setAttrList(infoView.getGoodsItem().getAttrList());
                goodsItemEntity.setBrandName(infoView.getGoodsItem().getBrandName());
                goodsItemEntity.setFcategory(infoView.getGoodsItem().getFcategory());
                goodsItemEntity.setUnit(infoView.getGoodsItem().getUnit());
                goodsItemEntity.setBrandId(infoView.getGoodsItem().getBrandId());
                goodsItemEntity.setHaveAttribute(infoView.getGoodsItem().isHaveAttribute());
                goodsItemEntity.setScatName(infoView.getGoodsItem().getScatName());
                goodsItemEntity.setFcatName(infoView.getGoodsItem().getFcatName());
                goodsItemEntity.setScategory(infoView.getGoodsItem().getScategory());
                goodsItemEntity.setSort(infoView.getGoodsItem().getSort());
                goodsItemEntity.setTcatName(infoView.getGoodsItem().getTcatName());
                goodsItemEntity.setTcategory(infoView.getGoodsItem().getTcategory());
                return goodsItemEntity;
            }
        } else {
            return new GoodsItemEntity();
        }
    }

    private Serializable getCurrentGoodsView(InquiryGoodsItemView mGoodsInfoView) {
        if (mGoodsInfoView.isChoiceST()) {
            mGoodsInfoView.getConcreteItem().setNum(mGoodsInfoView.getGoodsAmount());
            return mGoodsInfoView.getConcreteItem();
        } else {
            mGoodsInfoView.getGoodsItem().setNum(mGoodsInfoView.getGoodsAmount());
            return mGoodsInfoView.getGoodsItem();
        }
    }

    /**
     * 选择地区后请求的经纬度
     */
    private void fillCurrentAddressLadling(MapLongAndLatEntity data) {
        this.currentSelectedLang = data;
    }

    /**
     * 展示城市弹窗
     */
    private void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                //区
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDistrictName(areaName);
                Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String content;
            if (TextUtils.isEmpty(areaName)) {
                content = addressEntityList.get(options1).getName()
                        + "-" + opt2.get(options1).get(options2).getName();
            } else {
                content = addressEntityList.get(options1).getName()
                        + "-" + opt2.get(options1).get(options2).getName()
                        + "-" + areaName;
            }
            mDataBinding.goodsReceiveArea.setContent(content);

            cityPosition1 = options1;
            cityPosition2 = options2;
            //省
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setProvinceName(addressEntityList.get(options1).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setProvinceNo(addressEntityList.get(options1).getNo());
            //市
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setCityName(opt2.get(options1).get(options2).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());

            currentCity = opt2.get(options1).get(options2).getName();
            if (TextUtils.isEmpty(areaName)) {
                mViewModel.getSelectedAddressLadling(addressEntityList.get(options1).getNo(), opt2.get(options1).get(options2).getNo(), "");
            } else {
                mViewModel.getSelectedAddressLadling(addressEntityList.get(options1).getNo(), opt2.get(options1).get(options2).getNo(), opt3.get(options1).get(options2).get(options3).getNo());
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setTitleText("选择收货地区");
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    /**
     * 发货地  +  目的地  联合使用
     *
     * @param data 三级地址
     */
    private void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(() -> {
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;
                default:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            /**
             * 区域列表
             */
            List<List<AddressEntity>> areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        if (view.getId() == R.id.goods_end_time) {
            showDatePop();
        } else if (view.getId() == R.id.goods_receive_area) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                mViewModel.getAddressModel();
            }
        } else if (view.getId() == R.id.goods_receive_address) {
            // 跳转地址选择页面 ，携带地址回来
            if (TextUtils.isEmpty(mDataBinding.goodsReceiveArea.getContent())) {
                MToast.showToast(this, "请选择收货地区");
                return;
            }
            Intent intent1 = new Intent(this, SelectAddressActivity.class);
            intent1.putExtra(SelectAddressActivity.TITLE, "收货地址定位");
            intent1.putExtra(SelectAddressActivity.HINT, "请输入地址");
            intent1.putExtra(SelectAddressActivity.SAVE_TEXT, "保存为收货地址");
            intent1.putExtra(SelectAddressActivity.CITY, currentCity);
            if (!TextUtils.isEmpty(currentSelectedLang.getLat())) {
                intent1.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(currentSelectedLang.getLat()));
            }
            if (!TextUtils.isEmpty(currentSelectedLang.getLng())) {
                intent1.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(currentSelectedLang.getLng()));
            }
            startActivityForResult(intent1, REQUEST_CODE_SELECT_ADDRESS);
        } else if (view.getId() == R.id.goods_deliver_demand) {
            if (goodsDeliverDemandList != null) {
                showDeliverDemand();
            } else {
                mViewModel.getDeliverDemand(false);
            }
        } else if (view.getId() == R.id.goods_load_demand) {
            if (goodsLoadDemandList != null) {
                showLoadDemand();
            } else {
                mViewModel.getLoadDemand(false);
            }
        } else if (view.getId() == R.id.goods_unload_demand) {
            if (goodsUnloadDemandList != null) {
                showUnloadDemand();
            } else {
                mViewModel.getUnloadDemand(false);
            }
        } else if (view.getId() == R.id.goods_pay_type) {
            if (goodsPayTypeList != null) {
                showPayType();
            } else {
                mViewModel.getPayType(false);
            }
        } else if (view.getId() == R.id.goods_check_type) {
            if (goodsPriceCheckList != null) {
                showPriceCheck();
            } else {
                mViewModel.getPriceCheckDemand(false);
            }
        }
    }

    private void showDatePop() {
        AtomicInteger payPosition = new AtomicInteger();
        List<GoodsInquiryEndTimeEntity> endDateEntityList = new ArrayList<>();
        endDateEntityList.add(new GoodsInquiryEndTimeEntity("3天截止", "0"));
        endDateEntityList.add(new GoodsInquiryEndTimeEntity("7天截止", "1"));
        endDateEntityList.add(new GoodsInquiryEndTimeEntity("一个月截止", "2"));
        endDateEntityList.add(new GoodsInquiryEndTimeEntity("自定义", "3"));
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v1) -> {
            int index = Integer.parseInt(endDateEntityList.get(options1).getNo());
            switch (index) {
                case 0:
                    setEndLineTimeDate(3);
                    break;
                case 1:
                    setEndLineTimeDate(7);
                    break;
                case 2:
                    setEndLineTimeDate(30);
                    break;
                case 3:
                    showTimePop();
                    break;
                default:
                    break;
            }
            payPosition.set(options1);
        }).setLineSpacingMultiplier(2.2f)
                .setCancelColor(0xFF666666)
                .setTitleColor(0xFF969696)
                .setSubCalSize(15)
                .setTitleSize(15)
                .setContentTextSize(15)
                .build();
        businessOption.setPicker(endDateEntityList);
        businessOption.setSelectOptions(payPosition.get());
        businessOption.setTitleText("选择截止日期");
        businessOption.show();
    }

    @SuppressLint("SimpleDateFormat")
    private void setEndLineTimeDate(int day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, day);
        String format = sdf.format(c.getTime());
        switch (day) {
            case 3:
                mDataBinding.goodsEndTime.setContent("3天截止");
                break;
            case 7:
                mDataBinding.goodsEndTime.setContent("7天截止");
                break;
            case 30:
                mDataBinding.goodsEndTime.setContent("一个月截止");
                break;
            default:
                break;
        }
        //时间戳
        long times = DateUtils.dateTo13Timestamp3(format);
        MLog.d(TAG, "releaseGoods shipTime is:" + times);
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeadlineTime(String.valueOf(times));
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    /**
     * 校验输入是否正确
     *
     * @return 输入是否正确
     */
    private boolean isInputValid() {
        if (TextUtils.isEmpty(mDataBinding.goodsEndTime.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择截止时间");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsReceiveArea.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择收货地区");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsReceiveAddress.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择详细地址");
            return false;
        }
        String goodsRate = mDataBinding.goodsRate.getContent();
        if (TextUtils.isEmpty(goodsRate)) {
            MToast.showToast(InquiryPublishingActivity.this, "请输入发票税率");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsDeliverDemand.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择送货要求");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsLoadDemand.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择装车方式");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsUnloadDemand.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择卸车方式");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsPayType.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择支付方式");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsCheckType.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请选择询价方式");
            return false;
        }
        if (TextUtils.isEmpty(mDataBinding.goodsContactName.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请输入联系人姓名");
            return false;
        }
        if (mDataBinding.goodsContactName.getContent().length() < 2) {
            MToast.showToast(InquiryPublishingActivity.this, "联系人为2-15个文字");
            return false;
        }
        if ("邀请询价".equals(mDataBinding.goodsCheckType.getContent())) {
            if (inviteCompanyList == null || inviteCompanyList.size() == 0) {
                MToast.showToast(InquiryPublishingActivity.this, "请添加您要邀请的供应商");
                return false;
            }
        }
        if (inviteCompanyList != null && inviteCompanyList.size() > 50) {
            MToast.showToast(InquiryPublishingActivity.this, "最多只能选择50家供应商");
            return false;
        }

        if (TextUtils.isEmpty(mDataBinding.goodsContactNumber.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "请输入联系电话");
            return false;
        }
        if (!CheckUtils.isMobileNum(mDataBinding.goodsContactNumber.getContent())) {
            MToast.showToast(InquiryPublishingActivity.this, "手机号格式不正确");
            return false;
        }
        return true;
    }

    /**
     * 添加商品方式的选择框
     */
    private void showAddGoodsPop() {
        if (!this.addGoodsPopWindow.isShowing()) {
            this.addGoodsPopWindow.showDownPopwindow(mDataBinding.goodsGrayView, true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_FIND_SUPPLIER) {
                if (data == null) {
                    LogUtil.d(TAG, "onActivityResult find supplier data is null");
                    return;
                }
                List<SupplierEntity> supplierEntityList = (List<SupplierEntity>) data.getSerializableExtra(FindInquirySupplierActivity.SUPPLIER_ENTITY);
                if (supplierEntityList == null || supplierEntityList.size() == 0) {
                    LogUtil.d(TAG, "onActivityResult, supplierEntityList is null or empty");
                    return;
                }
                mDataBinding.rlNoneSupplier.setVisibility(View.GONE);
                fillSupplierView(supplierEntityList);
            }
            if (requestCode == REQUEST_CODE_OPEN_FILE_CHOOSER) {
                if (data == null) {
                    LogUtil.d(TAG, "onActivityResult chooseFile data is null");
                    return;
                }
                handleFileChoose(data);
            }
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片、视频、音频选择结果回调
                localMedia = PictureSelector.obtainMultipleResult(data);
                albumAdapter.setActionEnable(false);
                mDataBinding.goodsUploadFile.setEnabled(false);
                mDataBinding.goodsUploadFile.getBackground().setAlpha(102);
                if (localMedia != null && localMedia.size() != 0) {
                    int index = 1;
                    boolean isEnd = false;
                    for (int i = 0; i < localMedia.size(); i++) {
                        if (localMedia.get(i).getRealPath() != null && !"".endsWith(localMedia.get(i).getRealPath())) {
                            File file = new File(localMedia.get(i).getRealPath());
                            if (i == localMedia.size() - 1) {
                                isEnd = true;
                            }
                            mViewModel.uploadSingleImage(file, index, isEnd);
                        }
                        index++;
                    }
                    localMedia.clear();
                } else {
                    albumAdapter.setActionEnable(true);
                    mDataBinding.goodsUploadFile.setEnabled(true);
                    mDataBinding.goodsUploadFile.getBackground().setAlpha(255);
                }
            }
            if (requestCode == REQUEST_CODE_SELECT_ADDRESS) {//选取地址返回
                if (data.hasExtra(SelectAddressActivity.CURRENT_POSITION)) {
                    mDataBinding.goodsReceiveAddress.setContent(data.getStringExtra(SelectAddressActivity.CURRENT_POSITION));
                }
            }

        }
    }

    /**
     * 填充UI供应商信息
     *
     * @param supplierEntityList 供应商列表
     */
    private void fillSupplierView(List<SupplierEntity> supplierEntityList) {
        for (SupplierEntity entity : supplierEntityList) {
            if (!supplierEntityArrayList.contains(entity)) {
                supplierEntityArrayList.add(entity);
            }
        }
        buildInvitedCompanyList(supplierEntityArrayList);
        if (supplierDataAdapter != null) {
            if (mDataBinding.goodsSupplierView.getVisibility() == View.GONE) {
                mDataBinding.goodsSupplierView.setVisibility(View.VISIBLE);
            }
            supplierDataAdapter.setNewData(supplierEntityArrayList);
        }
    }

    /**
     * 构建邀请公司列表
     *
     * @param supplierEntityArrayList 供应商列表
     */
    private void buildInvitedCompanyList(List<SupplierEntity> supplierEntityArrayList) {
        inviteCompanyList.clear();
        if (supplierEntityArrayList == null || supplierEntityArrayList.size() == 0) {
            LogUtil.d(TAG, "buildInvitedCompanyList supplierEntityArrayList is empty");
            return;
        }
        for (SupplierEntity entity : supplierEntityArrayList) {
            InvitedCompanyEntity company = new InvitedCompanyEntity();
            company.setSupplierName(entity.getName());
            company.setSupplier(entity.getNo());
            company.setFlag(entity.getFlag());
            company.setSupplierType(entity.getSupplierType());
            if (!inviteCompanyList.contains(company)) {
                inviteCompanyList.add(company);
            }
        }
    }

    /**
     * 处理文件
     *
     * @param data 文件
     */
    private void handleFileChoose(Intent data) {
        Uri uri = data.getData();
        if (uri == null) {
            return;
        }
        /**
         * 文件路径
         */
        String filePath;
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
            if (checkFileSize(filePath)) {
                mViewModel.uploadSingleImage(new File(filePath), 1, true);
                MToast.showToast(this, "图片上传完成...");
            }
            return;
        }
        filePath = FileUtils.getPath(this, uri);
        if (checkFileSize(filePath)) {
            mViewModel.uploadSingleImage(new File(filePath), 1, true);
        }
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private boolean checkFileSize(String filePath) {
        float sizeCount;
        long fileLength = AttachmentStore.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > 20) {
                    MToast.showToast(this, "可上传不超过20M的文件");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 增加商品类目
     *
     * @param context 上下文对象
     */
    private void addGoodsView(InquiryPublishingActivity context, Serializable serializable, boolean isCopy) {
        InquiryGoodsItemView goodsInfoView = new InquiryGoodsItemView(context, mDataBinding.goodsGrayView);
        goodsCount++;
        goodsInfoView.setCurrentViewTag(goodsCount);
        goodsInfoView.initGoodsModel(serializable, isCopy);
        goodsInfoView.setTransferClickEventListener(context);
        goodsInfoView.setTitle("商品(" + goodsCount + ")");
        mDataBinding.llGoodsInfo.addView(goodsInfoView);
        goodsViewList.add(goodsCount - 1, goodsInfoView);
        if (goodsCount > MIN_GOODS_COUNT) {
            for (int a = 0; a < goodsViewList.size(); a++) {
                goodsViewList.get(a).setDeleteVisibility(true);
            }
        } else {
            for (int a = 0; a < goodsViewList.size(); a++) {
                goodsViewList.get(a).setDeleteVisibility(false);
            }
        }
        if (goodsCount == MAX_GOODS_COUNT) {
            mDataBinding.goodsAddGoods.setVisibility(View.GONE);
        }
    }

    /**
     * 删除商品类目
     */
    private void removeGoodsItem(InquiryGoodsItemView mGoodsInfoView) {
        if (goodsViewList.size() >= goodsCount && mGoodsInfoView != null) {
            mDataBinding.llGoodsInfo.removeView(mGoodsInfoView);
            if (goodsViewList.contains(mGoodsInfoView)) {
                goodsViewList.remove(mGoodsInfoView);
                this.mGoodsInfoView = null;
            }
        }
        int num = 0;
        int newCount = goodsViewList.size();
        if (newCount > 0) {
            for (int index = 0; index < newCount; index++) {
                num++;
                goodsViewList.get(index).setTitle("商品(" + num + ")");
                goodsViewList.get(index).setCurrentViewTag(num);
            }
        }
        goodsCount--;
        mDataBinding.goodsAddGoods.setVisibility(View.VISIBLE);
        if (goodsCount > MIN_GOODS_COUNT) {
            for (int a = 0; a < goodsViewList.size(); a++) {
                goodsViewList.get(a).setDeleteVisibility(true);
            }
        } else {
            for (int a = 0; a < goodsViewList.size(); a++) {
                goodsViewList.get(a).setDeleteVisibility(false);
            }
        }
    }

    /**
     * 构建询价信息
     */
    private void buildPriceCheckData() {
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDetailAddress(mDataBinding.goodsReceiveAddress.getContent());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLatitude(currentSelectedLang.getLat());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLongitude(currentSelectedLang.getLng());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setTaxRate(mDataBinding.goodsRate.getContent());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDescribe(mDataBinding.goodsNote.getText().toString().trim());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setQualityDesc(mDataBinding.goodsRequirements.getText().toString().trim());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setFeaturesDesc(mDataBinding.goodsFeature.getText().toString().trim());
        /*2021.03.29 询价发布时，只传递个人认证用户姓名****/
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (1 == type || 2 == type || 3 == type) {
            String company = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setPublishUserName(company);
        } else {
            String realName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setPublishUserName(realName);
        }
        /*2021.03.29 询价发布时，只传递个人认证用户姓名****/
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setContacts(mDataBinding.goodsContactName.getContent());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setContactNumber(mDataBinding.goodsContactNumber.getContent());
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setFilePath(fileItemInformation);
        Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setInviteCompanyList(inviteCompanyList);
        if ("2".equals(fromWhere)) {
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setNo("");
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setId("0");
        } else {
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setNo(this.resourceId);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setId(this.resourceId);
        }
    }

    /**
     * 改变未填写数据得状态
     */
    private void changeGoodsStates() {
        if (goodsViewList.size() > 0) {
            for (InquiryGoodsItemView view : goodsViewList) {
                view.isInputValid();
            }
        }
    }

    /**
     *
     */
    private boolean isFillGoods() {
        if (goodsViewList.size() > 0) {
            for (InquiryGoodsItemView view : goodsViewList) {
                if (!view.isChoiceST()) {
                    if (TextUtils.isEmpty(view.getGoodsItem().getFcatName()) || TextUtils.isEmpty(view.getGoodsItem().getScatName()) || TextUtils.isEmpty(view.getGoodsItem().getTcatName())) {
                        return false;
                    }
                    if (view.getGoodsItem().isHaveAttribute() && view.getGoodsItem().getAttrList() == null) {
                        return false;
                    }
                    if (view.getGoodsItem().isHaveAttribute() && view.getGoodsItem().getAttrList().size() == 0) {
                        return false;
                    }
                    if (TextUtils.isEmpty(view.getGoodsItem().getNum())) {
                        return false;
                    }
                    if (TextUtils.isEmpty(view.getGoodsItem().getUnit())) {
                        return false;
                    }
                } else {
                    if (TextUtils.isEmpty(view.getConcreteItem().getFcatName()) || TextUtils.isEmpty(view.getConcreteItem().getScatName()) || TextUtils.isEmpty(view.getConcreteItem().getTcatName())) {
                        return false;
                    }
                    if (view.getConcreteItem().getAdmixtureFactList() == null) {
                        return false;
                    }
                    if (view.getConcreteItem().getAdmixtureFactList().size() == 0) {
                        return false;
                    }
                    if (TextUtils.isEmpty(view.getConcreteItem().getNum())) {
                        return false;
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * view绑定的数据拼接起来，商品列表的集合
     */
    private List<GoodsItemEntity> buildGoodsList() {
        List<GoodsItemEntity> goodsItemList = new ArrayList<>();
        if (goodsViewList.size() > 0) {
            for (InquiryGoodsItemView view : goodsViewList) {
                if (!view.isChoiceST()) {
                    view.getGoodsItem().setNum(view.getGoodsAmount());
                    goodsItemList.add(view.getGoodsItem());
                }
            }
        }
        return goodsItemList;
    }

    /**
     * view绑定的数据拼接起来，商品列表的集合
     */
    private List<ConcreteEntity> buildConcreteList() {
        List<ConcreteEntity> concreteList = new ArrayList<>();
        if (goodsViewList.size() > 0) {
            for (InquiryGoodsItemView view : goodsViewList) {
                if (view.isChoiceST()) {
                    view.getConcreteItem().setNum(view.getGoodsAmount());
                    concreteList.add(view.getConcreteItem());
                }
            }
        }
        return concreteList;
    }

    /**
     * 时间选择器
     */
    private void showTimePop() {
        selectedDate = Calendar.getInstance();
        selectedDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        TimePickerView timePicker = new TimePickerBuilder(InquiryPublishingActivity.this, (date, v) -> {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdfShow = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String format = sdf.format(date);
            if (today == null) {
                today = new Date();
            }
            int compareTo = today.compareTo(date);
            if (compareTo >= 0) {
                Toast.makeText(InquiryPublishingActivity.this, "请选择大于当前时间", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    mDataBinding.goodsEndTime.setContent(sdfShow.format(date));
                    selectedDate.setTime(date);
                    //时间戳
                    long times = DateUtils.dateTo13Timestamp3(format);
                    MLog.d(TAG, "releaseGoods shipTime is:" + times);
                    Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeadlineTime(String.valueOf(times));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setType(new boolean[]{true, true, true, true, true, false}).build();
        timePicker.show();
        timePicker.setTitleText("请选择日期");
        timePicker.setDate(selectedDate);
    }

    /**
     * 显示送货要求
     */
    private void showDeliverDemand(List<GoodsInfoTypeEntity> data, boolean isF) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.goodsDeliverDemandList = data;
        if (isF) {
            mDataBinding.goodsDeliverDemand.setContent(data.get(0).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeliveryRequire(goodsDeliverDemandList.get(0).getNo());
            goodsDeliverDemandPosition = 0;
        } else {
            showDeliverDemand();
        }
    }

    /**
     * 显示送货选择框
     */
    private void showDeliverDemand() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v) -> {
            String content = goodsDeliverDemandList.get(options1).getName();
            mDataBinding.goodsDeliverDemand.setContent(content);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setDeliveryRequire(goodsDeliverDemandList.get(options1).getNo());
            goodsDeliverDemandPosition = options1;
        }).build();
        businessOption.setPicker(goodsDeliverDemandList);
        businessOption.setTitleText("送货要求");
        businessOption.setSelectOptions(goodsDeliverDemandPosition);
        businessOption.show();
    }

    /**
     * 显示装车方式
     */
    private void showLoadDemand(List<GoodsInfoTypeEntity> data, boolean isF) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.goodsLoadDemandList = data;
        if (isF) {
            mDataBinding.goodsLoadDemand.setContent(data.get(0).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLoadingRequire(goodsLoadDemandList.get(0).getNo());
            goodsLoadDemandPosition = 0;
        } else {
            showLoadDemand();
        }
    }

    /**
     * 显示装车方式选择框
     */
    private void showLoadDemand() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v) -> {
            String content = goodsLoadDemandList.get(options1).getName();
            mDataBinding.goodsLoadDemand.setContent(content);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setLoadingRequire(goodsLoadDemandList.get(options1).getNo());
            goodsLoadDemandPosition = options1;
        }).build();
        businessOption.setPicker(goodsLoadDemandList);
        businessOption.setTitleText("装车要求");
        businessOption.setSelectOptions(goodsLoadDemandPosition);
        businessOption.show();
    }

    /**
     * 显示卸车方式
     */
    private void showUnloadDemand(List<GoodsInfoTypeEntity> data, boolean isF) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.goodsUnloadDemandList = data;
        if (isF) {
            mDataBinding.goodsUnloadDemand.setContent(data.get(0).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setUnloadRequire(goodsUnloadDemandList.get(0).getNo());
            goodsUnloadDemandPosition = 0;
        } else {
            showUnloadDemand();
        }
    }

    /**
     * 显示卸车方式选择框
     */
    private void showUnloadDemand() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v) -> {
            String content = goodsUnloadDemandList.get(options1).getName();
            mDataBinding.goodsUnloadDemand.setContent(content);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setUnloadRequire(goodsUnloadDemandList.get(options1).getNo());
            goodsUnloadDemandPosition = options1;
        }).build();
        businessOption.setPicker(goodsUnloadDemandList);
        businessOption.setTitleText("卸车要求");
        businessOption.setSelectOptions(goodsUnloadDemandPosition);
        businessOption.show();
    }

    /**
     * 付款方式
     */
    private void showPayType(List<GoodsInfoTypeEntity> data, boolean isF) {
        if (data == null || data.size() == 0) {
            return;
        }
        this.goodsPayTypeList = data;
        if (isF) {
            mDataBinding.goodsPayType.setContent(data.get(0).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setTransactionMethod(goodsPayTypeList.get(0).getNo());
            goodsPayTypePosition = 0;
        } else {
            showPayType();
        }
    }

    /**
     * 付款方式选择框
     */
    private void showPayType() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v) -> {
            String content = goodsPayTypeList.get(options1).getName();
            mDataBinding.goodsPayType.setContent(content);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setTransactionMethod(goodsPayTypeList.get(options1).getNo());
            goodsPayTypePosition = options1;
        }).build();
        businessOption.setPicker(goodsPayTypeList);
        businessOption.setTitleText("付款方式");
        businessOption.setSelectOptions(goodsPayTypePosition);
        businessOption.show();
    }

    /**
     * 询价方式
     */
    private void showPriceCheck(List<GoodsInfoTypeEntity> data, boolean isF) {
        if (data == null || data.size() == 0) {
            return;
        }
        Iterator<GoodsInfoTypeEntity> it = data.iterator();
        while (it.hasNext()) {
            GoodsInfoTypeEntity item = it.next();
            if ("会员询价".equals(item.getName())) {
                it.remove();
            }
        }
        this.goodsPriceCheckList = data;
        if (isF) {
            mDataBinding.goodsCheckType.setContent(data.get(0).getName());
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setType(goodsPriceCheckList.get(0).getNo());
            goodsPriceCheckPosition = 0;
        } else {
            showPriceCheck();
        }
    }

    /**
     * 询价方式选择框
     */
    private void showPriceCheck() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(InquiryPublishingActivity.this, (options1, options2, options3, v) -> {
            String content = goodsPriceCheckList.get(options1).getName();
            mDataBinding.goodsCheckType.setContent(content);
            Objects.requireNonNull(mViewModel.priceCheckEntity.get()).setType(goodsPriceCheckList.get(options1).getNo());
            goodsPriceCheckPosition = options1;
            if ("会员询价".equals(content)) {
                mViewModel.getVipSupplier();
            }
        }).build();
        businessOption.setPicker(goodsPriceCheckList);
        businessOption.setTitleText("询价方式");
        businessOption.setSelectOptions(goodsPriceCheckPosition);
        businessOption.show();
    }

    /**
     * 会员供应商列表
     */
    private void showVipSupplier(List<SupplierEntity> data) {
        if (data == null || data.size() == 0) {
            mDataBinding.rlNoneSupplier.setVisibility(View.VISIBLE);
            if (!supplierEntityArrayList.isEmpty()) {
                supplierEntityArrayList.clear();
            }
            if (supplierDataAdapter != null) {
                if (mDataBinding.goodsSupplierView.getVisibility() == View.GONE) {
                    mDataBinding.goodsSupplierView.setVisibility(View.VISIBLE);
                }
                supplierDataAdapter.setNewData(supplierEntityArrayList);
            }
            inviteCompanyList.clear();
            return;
        }
        if (!supplierEntityArrayList.isEmpty()) {
            supplierEntityArrayList.clear();
        }
        SupplierEntity supplierEntity;
        for (SupplierEntity entity : data) {
            supplierEntity = new SupplierEntity();
            supplierEntity.setSelected(true);
            supplierEntity.setFlag(entity.getFlag());
            supplierEntity.setNo(entity.getNo());
            supplierEntity.setName(entity.getName());
            supplierEntityArrayList.add(supplierEntity);
        }
        buildInvitedCompanyList(supplierEntityArrayList);
        if (supplierDataAdapter != null) {
            if (mDataBinding.goodsSupplierView.getVisibility() == View.GONE) {
                mDataBinding.goodsSupplierView.setVisibility(View.VISIBLE);
            }
            supplierDataAdapter.setNewData(supplierEntityArrayList);
        }
    }

    /**
     * 当前编辑商品的view点击回调
     *
     * @param viewId         viewId
     * @param currentViewTag 当前编辑View的TAG
     */
    @SuppressLint("NonConstantResourceId")
    @Override
    public void transfer(int viewId, int currentViewTag) {
        mGoodsInfoView = Objects.requireNonNull(goodsViewList.get(currentViewTag - 1));
        if (viewId == R.id.goods_delete) {
            removeGoodsItem(mGoodsInfoView);
        }
    }

    private void openAlbum() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .maxSelectNum(MAX_COUNT - fileItemInformation.size())//判断还能选多少张图片
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .selectionMedia(localMedia)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 上传图片
     *
     * @param url 服务器图片地址
     * @param
     */
    private void uploadImageSuccess(String url, File file, int num, boolean isEnd) {
        if (TextUtils.isEmpty(url)) {
            MToast.showToast(this, "图片" + num + "上传失败...");
        } else {
            FileItemInfoEntity information = new FileItemInfoEntity();
            information.setUrl(url);
            information.setFileName(file.getName());
            information.setSize(file.length());
            fileItemInformation.add(information);
            if (albumAdapter != null) {
                albumAdapter.setNewData(fileItemInformation);
            }
        }
        if (isEnd) {
            assert albumAdapter != null;
            albumAdapter.setActionEnable(true);
            setUploadButtonEnable();
        }
    }

    private void setUploadButtonEnable() {
        mDataBinding.goodsUploadFile.setEnabled(fileItemInformation.size() < 10);
        if (mDataBinding.goodsUploadFile.isEnabled()) {
            mDataBinding.goodsUploadFile.getBackground().setAlpha(255);
        } else {
            mDataBinding.goodsUploadFile.getBackground().setAlpha(102);
        }
    }

}